//
//  ARConfigManager.swift
//  AquaRaft
//
//  Created by 何启亮 on 2024/3/25.
//

import Foundation
import Alamofire

/// AppConfig
class ARConfigManager {
    
    // MARK: - Public property
    
    var ver: String {
        if let _ver = _ver {
            return _ver
        }
        return "0"
    }
    
    var autoTranslate: Bool {
        didSet {
            UserDefaults.standard.set(autoTranslate, forKey: Self.autoTranslateKey)
            UserDefaults.standard.synchronize()
        }
    }
    
    // Private property
    
    static let verKey = "AR.configManager.verKey"
    static let autoTranslateKey = "AR.configManager.autoTranslateKey"
    private var _ver: String?
    private var _configItems: [ARConfigItem]?
    
    // 单例
    
    static let share = ARConfigManager()
    
    private init() {
        
        if let ver = UserDefaults.standard.string(forKey: Self.verKey) {
            _ver = ver
        }
        self.autoTranslate = false
        if let _ = UserDefaults.standard.object(forKey: Self.autoTranslateKey) {
            self.autoTranslate = UserDefaults.standard.bool(forKey: Self.autoTranslateKey)
        }
        
        self.configManager()
    }
    
    private func configManager() {
        
        // Do something...
    }
    
    // MARK: - Action
    
    func fetchAppConfigIfCan() {
        if !self._fetchAppConfigIfCan() {
            // 添加通知
            NotificationCenter.default.addObserver(self, selector: #selector(onUUIDUpdateNotifictionHandler(_:)), name: ARDevice.uuidUpdateNotification, object: nil)
        }
    }
    
    private func _fetchAppConfigIfCan() -> Bool {
        if let _ = ARDevice.share.uuidResult.idfa {
            ARConfigRequest().request(of: ARConfigRequestResponse.self) { [weak self] response, result in
                switch result {
                case .faild(let err):
                    debugPrint("请求失败: \(err)")
                    break
                case .success(let apiResponse):
                    debugPrint("请求成功: \(apiResponse)")
                    // 查找
                    for item in apiResponse.items {
                        if case let .string(value) = item.data, item.name == "google_translation_key" {
                            ARTranslateUtil.share.translateKey = value
                            break
                        }
                    }
                    // 记录ver
                    self?._ver = apiResponse.ver
                    self?._configItems = apiResponse.items
                    UserDefaults.standard.set(apiResponse.ver, forKey: Self.verKey)
                    UserDefaults.standard.synchronize()
                    
                    break
                case .successWithoutResponse:
                    debugPrint("请求成功: null")
                    break
                }
            }
            return true
        }
        return false
    }
    
    // MARK: - Notification
    
    @objc private func onUUIDUpdateNotifictionHandler(_ noti: Notification) {
        let _ = self.fetchAppConfigIfCan()
    }
    
}

// MARK: - Define

class ARConfigRequest: ARRequest {
    
    override var api: String {
        get {
            return "/config/getAppConfig"
        }
    }
}

class ARConfigRequestResponse: Decodable {
    var ver: String
    var items: [ARConfigItem]
}

/// item
class ARConfigItem: Decodable {
    var name: String
    var data: AnyDecodable
}
